<template>
  <div style="padding: 20px">
    <el-form label-position="left" :inline="true">
      <el-form-item label="食物种类">
        <el-select
          v-model="query.categoryId"
          placeholder="请选择食物种类"
          size="mini"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="食物分类">
        <el-select
          v-model="query.tag"
          placeholder="请选择食物分类"
          size="mini"
          multiple
        >
          <el-option label="早餐" value="早餐" />
          <el-option label="午餐" value="午餐" />
          <el-option label="晚餐" value="晚餐" />
          <el-option label="加餐" value="加餐" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="fetchDishes"
          >搜索</el-button
        >
        <el-button size="mini" @click="resetQuery">重置</el-button>
        <el-button type="primary" size="mini" @click="openDialog()"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 表格部分 -->
    <el-table :data="dishes" style="width: 100%; margin-top: 20px">
      <el-table-column prop="name" label="菜名" />
      <el-table-column label="分类" prop="tag"> </el-table-column>
      <el-table-column label="种类">
        <template slot-scope="scope">
          {{ scope.row.category?.categoryName || "--" }}
        </template>
      </el-table-column>
      <el-table-column label="图片">
        <template slot-scope="scope">
          <el-image
            :src="scope.row.imageUrl"
            style="width: 50px; height: 50px"
          />
        </template>
      </el-table-column>
      <el-table-column label="营养参数">
        <template slot-scope="scope">
          <el-button type="text" @click="openNutrition(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="炎症参数">
        <template slot-scope="scope">
          <el-button type="text" @click="openInflammation(scope.row)"
            >详情</el-button
          >
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="primary" @click="openDialog(scope.row)" size="mini"
            >编辑</el-button
          >
          <el-button type="danger" @click="deleteDish(scope.row)" size="mini"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div style="margin-top: 15px; text-align: right">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="form.foodId ? '编辑食物配置' : '添加食物配置'"
      :visible.sync="dialogVisible"
      width="800px"
    >
      <el-form
        :model="form"
        label-width="140px"
        size="small"
        label-position="left"
      >
        <div style="padding: 0 35px">
          <div style="display: flex; gap: 12px; justify-content: space-between">
            <el-form-item label="食物图片">
              <Upload
                @upload="handleFileUpload"
                :imageUrl="form.imageUrl"
              ></Upload>
            </el-form-item>

            <div>
              <el-form-item label="食物名称">
                <el-input v-model="form.name" placeholder="请输入食物名称" />
              </el-form-item>

              <el-form-item label="食物种类">
                <el-select
                  v-model="form.categoryId"
                  placeholder="请选择分类"
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in categoryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="食物分类">
                <el-select v-model="form.tag" placeholder="请选择分类" multiple>
                  <el-option label="早餐" value="早餐" />
                  <el-option label="午餐" value="午餐" />
                  <el-option label="晚餐" value="晚餐" />
                  <el-option label="加餐" value="加餐" />
                </el-select>
              </el-form-item>

              <el-form-item label="食物单位">
                <el-input v-model="form.unit" placeholder="请输入食物单位" />
              </el-form-item>
            </div>
          </div>
          <div
            v-for="(nutrient, index) in form.microElement"
            :key="index"
            style="
              display: flex;
              align-items: center;
              gap: 12px;
              justify-content: space-between;
            "
          >
            <el-form-item :label="nutrient.label + '含量'">
              <el-input-number
                v-model="nutrient.amount"
                :precision="1"
                :min="0"
                controls-position="right"
              />
            </el-form-item>
            <el-form-item :label="nutrient.label + '单位'">
              <el-input v-model="nutrient.unit" controls-position="right" />
            </el-form-item>
          </div>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveForm">确认</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="params.title"
      :visible.sync="params.visible"
      width="580px"
    >
      <div
        style="
          display: grid;
          grid-template-columns: 1fr 1fr;
          gap: 12px;
          font-size: 18px;
        "
      >
        <div
          v-for="content of params.content"
          style="display: flex; gap: 4px; padding: 4px"
        >
          <div style="min-width: 150px; text-align: left">
            {{ `${content.label}：` }}
          </div>
          <div>{{ content.amount }}</div>
          <div>{{ content.unit }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="onCLoseParamsDialog">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Upload from "@/comp/Upload";
export default {
  data() {
    return {
      dialogVisible: false,
      dishes: [],
      categoryOptions: [],
      categoryMap: {}, // 分类映射对象
      // 分页相关变量
      currentPage: 1,
      pageSize: 10,
      total: 0,
      query: {},
      form: {
        foodId: null,
        name: "",
        categoryId: null, // 用于存储选中的分类ID
        imageUrl: "",
        tag: "",
        unit: "",
        microElement: [],
      },
      nutrientTypes: [
        { type: "CALORIES", label: "热量", recommend: "0.180", unit: "千卡" },
        { type: "CARBS", label: "碳水化合物", recommend: "0.109", unit: "克" },
        { type: "PROTEIN", label: "蛋白质", recommend: "0.049", unit: "克" },
        {
          type: "CHOLESTEROL",
          label: "胆固醇",
          recommend: "0.347",
          unit: "毫克",
        },
        { type: "FAT", label: "脂肪", recommend: "0.298", unit: "克" },
        { type: "FIBER", label: "纤维素", recommend: "-0.663", unit: "g" },
        { type: "FOLATE", label: "叶酸", recommend: "-0.207", unit: "μg" },
        { type: "IRON", label: "铁", recommend: "0.032", unit: "mg" },
        { type: "MAGNESIUM", label: "镁", recommend: "-0.484", unit: "mg" },
        {
          type: "VITAMINB12",
          label: "维生素 B12",
          recommend: "0.205",
          unit: "μg",
        },
        {
          type: "VITAMINB6",
          label: "维生素 B6",
          recommend: "-0.379",
          unit: "mg",
        },
        {
          type: "BETACAROTENE",
          label: "β-胡萝卜素",
          recommend: "-0.584",
          unit: "μg",
        },
        {
          type: "MUFA",
          label: "单不饱和脂肪酸",
          recommend: "-0.019",
          unit: "g",
        },
        { type: "NIACIN", label: "烟酸", recommend: "-1", unit: "mg" },
        { type: "OMEGA3", label: "n-3 脂肪酸", recommend: "-0.436", unit: "g" },
        {
          type: "PUFA",
          label: "多不饱和脂肪酸",
          recommend: "-0.337",
          unit: "g",
        },
        {
          type: "RIBOFLAVIN",
          label: "核黄素",
          recommend: "-0.727",
          unit: "mg",
        },
        { type: "SFA", label: "饱和脂肪酸", recommend: "0.429", unit: "g" },
        { type: "SELENIUM", label: "硒", recommend: "-0.191", unit: "μg" },
        { type: "THIAMINE", label: "硫胺", recommend: "-0.354", unit: "mg" },
        {
          type: "VITAMINA",
          label: "维生素 A",
          recommend: "-0.4.1",
          unit: "μg",
        },
        {
          type: "VITAMINC",
          label: "维生素 C",
          recommend: "-0.424",
          unit: "mg",
        },
        {
          type: "VITAMIND",
          label: "维生素 D",
          recommend: "-0.446",
          unit: "μg",
        },
        {
          type: "VITAMINE",
          label: "维生素 E",
          recommend: "-0.419",
          unit: "mg",
        },
        { type: "ZINC", label: "锌", recommend: "-0.313", unit: "mg" },
      ],
      params: {
        title: "",
        visible: false,
        content: [""],
      },
    };
  },
  components: {
    Upload,
  },
  mounted() {
    this.fetchDishes(); // 获取菜品列表
    this.getCategoryOptions();
    this.form.microElement = this.initMicroElement();
  },
  methods: {
    resetQuery() {
      this.query = {};
      this.fetchDishes();
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchDishes();
    },
    // 当前页码改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchDishes();
    },
    initMicroElement() {
      return this.nutrientTypes.map((item) => {
        return {
          type: item.type,
          amount: 0,
          inflammationIndex: 0,
          unit: "",
          label: item.label,
        };
      });
    },
    /* 获取菜品列表 */
    async fetchDishes() {
      const response = await this.$http.get("/diet/admin/food", {
        params: {
          pageNo: this.currentPage,
          pageSize: this.pageSize,
          ...this.query,
        },
      });
      if (response.code) return this.$message.error(response.msg);
      this.dishes = response.data.list || [];
      this.total = response.data.total || 0;
    },

    /* 获取分类下拉 */
    async getCategoryOptions() {
      const { data, msg, code } = await this.$http.get("/diet/admin/category");
      if (code) return this.$message.error(msg);

      // 将分类数据转换为下拉选项需要的格式
      this.categoryOptions = (data || []).map((item) => {
        this.categoryMap[item.categoryId] = item.categoryName;
        return {
          value: item.categoryId, // 假设后端返回的分类ID字段是categoryId
          label: item.categoryName, // 假设后端返回的分类名称字段是categoryName
        };
      });
    },

    /* 根据分类ID获取分类名称 */
    getCategoryName(categoryId) {
      return this.categoryMap[categoryId] || "未知分类";
    },
    /* 打开弹窗 */
    openDialog(row) {
      if (row) {
        // 如果是编辑操作，将当前行的数据填充到表单中
        this.form = {
          foodId: row.foodId,
          name: row.name,
          categoryId: row.categoryId, // 填充分类ID
          imageUrl: row.imageUrl,
          tag: row.tag.split("、"),
          unit: row.unit,
          microElement: this.initMicroElement().map((item) => {
            const microElement = row.microElement.find(
              (micro) => micro.type === item.type
            );
            if (microElement) {
              return { ...item, ...microElement };
            }
            return item;
          }),
        };
      } else {
        // 如果是新增操作，重置表单
        this.resetForm();
      }
      this.dialogVisible = true;
    },
    resetForm() {
      this.form = {
        foodId: null,
        name: "",
        categoryId: null, // 重置分类ID
        imageUrl: "",
        microElement: this.initMicroElement(),
      };
    },
    /* 保存 */
    async saveForm() {
      // 表单验证
      if (!this.form.name) {
        return this.$message.error("食物名称不能为空");
      }
      if (!this.form.categoryId) {
        return this.$message.error("请选择食物种类");
      }
      if (!this.form.imageUrl) {
        return this.$message.error("请上传食物图片");
      }

      const formData = { ...this.form };
      if (!formData.foodId) {
        delete formData.foodId;
      }

      let url = "";
      let method = "post";

      if (formData.foodId) {
        url = `/diet/admin/food/${formData.foodId}`;
        method = "put";
      } else {
        url = "/diet/admin/food";
        method = "post";
      }

      const { msg, code } = await this.$http[method](url, {
        ...formData,
        tag: formData.tag.join(","),
      });
      if (code) return this.$message.error(msg);
      this.$message.success("保存成功");
      this.dialogVisible = false;
      this.fetchDishes(); // 重新拉列表
    },
    /* 删除 */
    async deleteDish(row) {
      this.$confirm("此操作将永久删除该食物, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { msg, code } = await this.$http.delete(
            `/diet/admin/food/${row.foodId}`
          );
          if (code) return this.$message.error(msg);
          this.$message.success("删除成功");
          this.fetchDishes(); // 刷新列表
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    /* 查看营养参数详情 */
    openNutrition(row) {
      this.params.title = "营养参数";
      this.params.content = row.microElement.map((item) => {
        const targetType = this.nutrientTypes.find(
          (nt) => nt.type === item.type
        );
        return {
          label: targetType?.label ?? "未知元素",
          amount: item.amount ?? 0,
          unit: item.unit ?? "",
        };
      });
      this.params.visible = true;
    },
    /* 查看炎症参数详情 */
    openInflammation(row) {
      this.params.title = "炎症参数";
      this.params.content = this.nutrientTypes.map((item) => {
        return {
          label: item?.label ?? "未知元素",
          amount: item.recommend,
          unit: item.unit,
        };
      });
      this.params.visible = true;
    },
    /* 关闭弹窗 */
    onCLoseParamsDialog() {
      this.params.title = "";
      this.params.content = [];
      this.params.visible = false;
    },
    handleFileUpload(file) {
      const allowed_types = ["image/jpeg", "image/png", "video/mp4"];
      const file_size = 1024 * 1024 * 15; // 后端校验的是30m，前端允许调整到最大30m
      if (!allowed_types.includes(file.raw.type)) {
        return this.$message.error("无效的文件类型。只允许 JPEG、PNG、MP4");
      }

      if (file.size > file_size) {
        return this.$message.error(
          `文件大小超过限制。最大允许 ${(file_size / (1024 * 1024)).toFixed(
            0
          )}M`
        );
      }
      this.form.imageUrl = file.response?.data.filepath;
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.3s;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.image-preview {
  position: relative;
}

.image-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  gap: 10px;
  padding: 5px 0;
}

.image-actions i {
  color: white;
  font-size: 18px;
  cursor: pointer;
}
</style>
